package com.nl.bits;

public class CountOne {
	
	/**
	 * 计算数字中１的个数
	 * @param num
	 * @return
	 */
	public static int countOne(int num){
		int flag =1;
		int count=0;
		while(flag >0){
			if((flag&num)!=0){
				count++;
			}
			flag=flag<<1;
		}
		return count;
	}
	/**
	 * 核心
	 * @param num
	 * @return
	 */
	//整数减去１与这个整数做与运算相当于把其最右边的１之后的几位都变成０
	//1010 & 1001=1000
	public static int countOne2(int num){
		int tmp=num;
		int count=0;
		while(tmp!=0){
			count++;
			tmp=(tmp&(tmp-1));
		}
		return count;
	}
		
	/**
	 * 是否是２的整数次方	
	 * @return
	 */
	public static boolean isPower2(int num){
		//２的整数次方说明只有一个１
		return (num&(num-1))==0;
	}

	/**
	 * 修改二进制的多少位能转化成另一个数
	 * @param args
	 */
	public static int modifyTime(int m,int n){
		int tmp = (m^n);
		return countOne2(tmp);
	}

	//右移补符号位
	//左移补零
	public static void main(String[] args) {
		System.out.println(countOne(1));
		System.out.println(countOne2(1));
		//negtive
		System.out.println(1<<31);
		//positive
		System.out.println(1<<33);

		System.out.println(isPower2(4));
		System.out.println(isPower2(40));
	}

}
